package ru.poomsae.isap.Online

import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.DialogInterface
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import com.androidnetworking.AndroidNetworking
import com.androidnetworking.common.Priority
import com.androidnetworking.error.ANError
import com.androidnetworking.interfaces.JSONObjectRequestListener
import com.example.isap_wtf.Model.ApiEndPoint
import com.example.isap_wtf.Model.ParametrsISAP
import org.json.JSONObject
import ru.poomsae.isap.Model.*
import ru.poomsae.isap.Online.Freestyle.Freestyle
import ru.poomsae.isap.Online.Para.ParaAcc
import ru.poomsae.isap.Online.SystemCut.SystemOfCut
import ru.poomsae.isap.R


open class MainActivity : AppCompatActivity() {

    var mIDHost: String = ""
    var arrayList = ArrayList<Kort>()
    var arrayListA = ArrayList<KortA>()
    var arraySudiList = ArrayList<Sudi>()
    var arraySudiListA = ArrayList<SudiA>()
    var arraySudiApultList = ArrayList<SudiApult>()
    var arrayID = ArrayList<String>()
    val APP_PREFERENCES = "mysettings"
    val APP_PREFERENCES_IDHOST = "idhostr"
    val APP_PREFERENCES_ARRAYID = "idarray"
    val APP_PREFERENCES_SETTING = "setting"
    var arrayIDHost: String = ""
    lateinit var pref: SharedPreferences
    var x: Int = 0
    lateinit var mJSONObject: JSONObject
    lateinit var kortCustom: AlertDialog
    lateinit var num_kort: String
    lateinit var kol_sud: String
    lateinit var sud: String
    lateinit var sys: String
    lateinit var settingSafe: String
    var host = "localhost"
    var chek: Int = 0
    var kol: Int = 0
    lateinit var ids: String
    var row: Int = 0
    lateinit var kortTextView: TextView
    lateinit var sudTextView: TextView
    lateinit var btnPara: Button
    lateinit var btnCut: Button
    lateinit var btnFree: Button
    private var countCort = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        pref = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE)
        kortTextView = findViewById(R.id.kortTextView)
        sudTextView = findViewById(R.id.sudTextView)

        btnPara = findViewById(R.id.btnPara)
        btnCut = findViewById(R.id.btnCut)
        btnFree = findViewById(R.id.btnFree)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.setting, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item?.itemId) {

            R.id.setting -> {
                idconn()
            }

        }

        return true
    }

    private fun loadKort() {
        println("MAinActivity loadKort chek = " + chek + " http://" + mIDHost + ApiEndPoint.KORT)
        AndroidNetworking.get("http://" + mIDHost + ApiEndPoint.KORT)
            .setPriority(Priority.MEDIUM)
            .build()
            .getAsJSONObject(object : JSONObjectRequestListener {
                override fun onResponse(response: JSONObject?) {
                    arrayListA.clear()
                    countCort = response?.getInt("countKort")!!.toInt()

                    val jsonArray = response?.optJSONArray("kort")
                    if (jsonArray?.length() == 0) {
                        Toast.makeText(
                            applicationContext,
                            "Download Court List",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                    for (i in 0 until jsonArray?.length()!!) {
                        val jsonObject = jsonArray?.optJSONObject(i)
                        println("MainActivity loadKort jsonObject = " + jsonObject)
                        arrayList.add(
                            Kort(
                                jsonObject.getInt("ids"),
                                jsonObject.getInt("kol"),
                                jsonObject.getInt("kol_sud"),
                                jsonObject.getInt("sys"),
                                jsonObject.getInt("nomer_kort")
                            )
                        )
                    }
                    viborKort()
                }

                override fun onError(anError: ANError?) {
                    val idserverDialog = AlertDialog.Builder(this@MainActivity)
                    val idserverDialogView = layoutInflater.inflate(R.layout.error_server, null)
                    idserverDialog.setView(idserverDialogView)
                    idserverDialog.setPositiveButton(
                        "Return",
                        { dialogInterface: DialogInterface, i: Int -> })
                    idserverDialog.setNegativeButton(
                        "Cancel",
                        { dialogInterface: DialogInterface, i: Int -> })
                    val idserverCustom = idserverDialog.create()
                    idserverCustom.show()
                    idserverCustom.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
                        idconn()
                        idserverCustom.dismiss()
                    }
                    idserverCustom.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener {
                        idserverCustom.dismiss()
                    }
                }
            })
    }

    private fun idconn() {
        val idserverDialog = AlertDialog.Builder(this)
        val idserverDialogView = layoutInflater.inflate(R.layout.idserver, null)
        val idserv = idserverDialogView.findViewById<EditText>(R.id.edit_idserver)
        val idSpinner = idserverDialogView.findViewById<Spinner>(R.id.spinner)
        if (mIDHost != "") {
            idserv.setText(mIDHost)
            val adapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayID)
            idSpinner.setAdapter(adapter)
        }
        idSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                idserv.setText(idSpinner.selectedItem.toString())
            }
        }
        idserverDialog.setView(idserverDialogView)
        idserverDialog.setPositiveButton("OK", { dialogInterface: DialogInterface, i: Int -> })
        val idserverCustom = idserverDialog.create()
        idserverCustom.show()
        idserverCustom.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
            if (idserv.text.length > 7) {
                host = idserv.text.toString()
                if (mIDHost != idserv.text.toString()) {
                    mIDHost = idserv.text.toString()
                        for (i in 0..arrayID.size - 1) {
                            if (mIDHost == arrayID[i]) {
                                x = i + 1
                            }
                        }
                        if (x > 0) {
                            arrayID.removeAt(x - 1)
                            x = 0
                        }
                        arrayID.add(mIDHost)
                        saveHost()
                        loadKort()
                        idserverCustom.dismiss()
                    } else {
                    loadKort()
                    idserverCustom.dismiss()
                }
            } else {
                if (idserv.text.length == 4 && idserv.text.toString()?.equals("2912")) {
                    mIDHost = idserv.text.toString()
                    if (mIDHost != idserv.text.toString()) {
                        mIDHost = idserv.text.toString()
                        for (i in 0..arrayID.size-1) {
                            if (mIDHost == arrayID[i]) {
                                x = i+1
                            }
                        }
                        if (x > 0) {
                            arrayID.removeAt(x-1)
                            x = 0
                        }
                        arrayID.add(mIDHost)
                        saveHost()

                    }
                    mIDHost = "poomsae.ru/cpt"
                    loadKort()
                    idserverCustom.dismiss()
                }
            }
        }
    }

    private fun viborKort() {
        val kortDialog = AlertDialog.Builder(this)
        val kortDialogView = layoutInflater.inflate(R.layout.kort_dialog, null)
        kortDialog.setView(kortDialogView)
        kortCustom = kortDialog.create()
        kortCustom.show()
        val kortLinearLayout = kortDialogView.findViewById<LinearLayout>(R.id.kortConn)

        for (i in 0..arrayList?.size - 1) {
            ids = (arrayList?.get(i)?.ids).toString()
            kol = arrayList?.get(i)?.kol
            num_kort = (arrayList?.get(i)?.nomer_kort).toString()
            kol_sud = (arrayList?.get(i)?.kol_sud).toString()
            sys = (arrayList?.get(i)?.sys).toString()
        }

        for(i in 0..countCort-1) {
            val kortButton = AppCompatButton(this)
            kortButton.setLayoutParams(
                LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT
                )
            )
            kortButton.id = i+1
            kortButton.text = resources.getText(R.string.kort).toString() + " " + (i+1)
            kortLinearLayout.addView(kortButton, i)
            if (num_kort.toInt() == i+1 && kol > kol_sud.toInt()) { kortButton.setEnabled(true); kortButton.setBackgroundResource(R.drawable.button_border_green) }
            else { kortButton.setEnabled(false); kortButton.setBackgroundResource(R.drawable.button_border) }
            kortButton.setOnClickListener {
                sudiload()
                kortCustom.dismiss()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        val editor = pref.edit()
        editor.putString(APP_PREFERENCES_IDHOST, mIDHost)
        editor.apply()
    }

    override fun onStop() {
        super.onStop()
        val editor = pref.edit()
        editor.putString(APP_PREFERENCES_IDHOST, mIDHost)
        editor.putString(APP_PREFERENCES_ARRAYID, arrayIDHost)
        editor.apply()
    }

    override fun onResume() {
        super.onResume()
        if (pref.contains(APP_PREFERENCES_IDHOST)) {
            mIDHost = pref.getString(APP_PREFERENCES_IDHOST, "localhost").toString()
            arrayIDHost = pref.getString(APP_PREFERENCES_ARRAYID, "localhost").toString()
            val x = arrayIDHost.replace("[",  "").replace(" ", "").replace("]", "")
            val array = x.split(",")
            for (i in 0..array.size-1) {
                arrayID.add(array[i])
            }
            arrayID.reverse()
        }
    }

    private fun saveHost() {
        arrayIDHost = arrayID.toString()
        val editor = pref.edit()
        editor.putString(APP_PREFERENCES_IDHOST, mIDHost)
        editor.putString(APP_PREFERENCES_ARRAYID, arrayIDHost)
        editor.apply()
    }

    private fun sudiload() {
        val loading = ProgressDialog(this)
        loading.setMessage("Download Judges List...")
        loading.show()

        AndroidNetworking.post("http://" + mIDHost + ApiEndPoint.CONNECT)
            .addBodyParameter("ids", ids)
            .setPriority(Priority.MEDIUM)
            .build()
            .getAsJSONObject(object : JSONObjectRequestListener {

                override fun onResponse(response: JSONObject?) {
                    loading.dismiss()
                    mJSONObject = response!!
                    sudivibor()
                }

                override fun onError(anError: ANError?) {
                    loading.dismiss()
                    Toast.makeText(applicationContext, "Ошибка подключения", Toast.LENGTH_SHORT)
                        .show()
                }
            })
    }

    private fun sudivibor() {
        println("sudivibor mJSONObject = " + mJSONObject)
        val sudiDialog = AlertDialog.Builder(this)
        val sudiDialogView = layoutInflater.inflate(R.layout.sudi_dialog, null)
        sudiDialog.setView(sudiDialogView)
        val sudiCustom = sudiDialog.create()
        sudiCustom.show()

        val sudiLinearLayout = sudiDialogView.findViewById<LinearLayout>(R.id.sudiCount)

        row = mJSONObject.getInt("row")
        val jsonArray = mJSONObject?.optJSONArray("kolsud")
        if(jsonArray?.length() == 0) {
            Toast.makeText(
                applicationContext,
                "Judge's Choice",
                Toast.LENGTH_SHORT
            ).show()
        }
        println("MainActivity sudivibor row = " + row + " kol = " + kol)
        if(row < kol) {
            for(i in 0..kol-1) {
                val sudiButton = AppCompatButton(this)
                sudiButton.setLayoutParams(
                    LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT
                    )
                )
                sudiButton.id = i+1
                sudiButton.text = resources.getText(R.string.sudi).toString() + " " + (i+1)
                sudiButton.setEnabled(true)
                sudiButton.setBackgroundResource(R.drawable.button_border_green)
                sudiLinearLayout.addView(sudiButton, i)
                for (j in 0 until jsonArray?.length()!!) {
                    val jsonObject = jsonArray?.optJSONObject(j)
                    if(jsonObject.getInt("conn_sud")  == i+1) {
                        sudiButton.setEnabled(false)
                        sudiButton.setBackgroundResource(R.drawable.button_border)
                    }
                }
                sudiButton.setOnClickListener {
                    sud = "1"
                    createsud()
                    sudiCustom.dismiss()
                }
            }
        }
    }

    private fun createsud() {
        kol_sud = kol.toString()
        val loading = ProgressDialog(this)
        loading.setMessage("Adding a judge...")
        loading.show()
        ParametrsISAP.idHostServer = mIDHost
        AndroidNetworking.post("http://" + mIDHost + ApiEndPoint.CREAT)
            .addBodyParameter("sud", sud)
            .addBodyParameter("ids", ids)
            .setPriority(Priority.MEDIUM)
            .build()
            .getAsJSONObject(object : JSONObjectRequestListener {

                override fun onResponse(response: JSONObject?) {
                    loading.dismiss()
                    Toast.makeText(
                        applicationContext,
                        "Judge № " + sud + " successfully connected",
                        Toast.LENGTH_SHORT
                    ).show()
                    when (sys) {
                        "1", "4" -> {
                            val btnCut = findViewById<Button>(R.id.btnCut)
                            btnCut.setEnabled(true)
                            btnCut.setBackgroundResource(R.drawable.button_border_green)
                            kortTextView.setText("Court № " + num_kort)
                            sudTextView.setText("Judges № " + sud)
                            ParametrsISAP.sys_sud = 1
                        }
                        "2" -> {
                            val btnFree = findViewById<Button>(R.id.btnFree)
                            btnFree.setEnabled(true)
                            btnFree.setBackgroundResource(R.drawable.button_border_green)
                            kortTextView.setText("Court № " + num_kort)
                            sudTextView.setText("Judges № " + sud)
                            ParametrsISAP.sys_sud = 2
                        }
                        "3" -> {
                            val btnPara = findViewById<Button>(R.id.btnPara)
                            btnPara.setEnabled(true)
                            btnPara.setBackgroundResource(R.drawable.button_border_green)
                            kortTextView.setText("Court № " + num_kort)
                            sudTextView.setText("Judges № " + sud)
                            ParametrsISAP.sys_sud = 3
                        }
                    }

                }

                override fun onError(anError: ANError?) {
                    loading.dismiss()
                    Toast.makeText(applicationContext, "Error adding judge", Toast.LENGTH_SHORT)
                        .show()
                }

            })

        btnCut.setOnClickListener {
            ParametrsISAP.kol_sud = kol_sud
            ParametrsISAP.numSud = sud
            val intent = Intent(this, SystemOfCut::class.java);
            startActivity(intent)
            finish()
        }
        btnFree.setOnClickListener {
            ParametrsISAP.kol_sud = kol_sud
            ParametrsISAP.numSud = sud
            val intent = Intent(this, Freestyle::class.java)
            startActivity(intent)
            finish()
        }
        btnPara.setOnClickListener {
            ParametrsISAP.kol_sud = kol_sud
            ParametrsISAP.numSud = sud
            val intent = Intent(this, ParaAcc::class.java)
            startActivity(intent)
            finish()
        }
    }

    fun setting_res() {

        val array = pref.getString(APP_PREFERENCES_SETTING, "localhost").toString().split(";")

        for (i in 0..array.size-1) {
            when (i) {
                0 -> { mIDHost = array[i]; if (mIDHost.equals("poomsae.ru/cpt")) host = "2912" }
                1 -> num_kort = array[i]
                2 -> kol_sud = array[i]
                3 -> sud = array[i]
                4-> sys = array[i]
            }
        }

        val settingDialog = AlertDialog.Builder(this)
        settingDialog.setTitle("Setting resume")
        settingDialog.setMessage("Host: " + host + "\n" + " Court № " + num_kort + "\n" + " Judges № " + sud)
        settingDialog.setPositiveButton("OK", {dialogInterface: DialogInterface, i: Int -> })
        settingDialog.setNegativeButton("Cancel", {dialog: DialogInterface?, which: Int ->  })
        val  settingCustom = settingDialog.create()
        settingCustom.show()
        settingCustom.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
            createsud()
            settingCustom.dismiss()
        }
        settingCustom.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener {
            idconn()
            settingCustom.dismiss()
        }

    }
}
